package com.bnz.controller;

import com.bnz.entity.Classes;
import com.bnz.entity.PageResult;
import com.bnz.entity.Student;
import com.bnz.entity.StudentVo;
import com.bnz.service.ClassesService;
import com.bnz.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private ClassesService classesService;


    //1. 列表学生
    @GetMapping("list")
    public String findAll(Model model){
        //1.1 查询所有学生
        List<Student> students = studentService.findAll();
        //1.2
        model.addAttribute("students",students);
        return "student/list";
    }

    //2. 分页查询
    @GetMapping("findByPage")
    public String findByPage(@RequestParam(defaultValue = "1",required = false) Integer page,
                                          @RequestParam(defaultValue = "3",required = false) Integer pageSiz,
                                          Model model){
        //2.1 分页查询学生列表
        PageResult<Student> pr = studentService.findByPage(page,pageSiz);
        model.addAttribute("pr",pr);
        //2.2 查询所有班级
        List<Classes> classes = classesService.findAll();
        model.addAttribute("classes",classes);
        return "student/list";
    }

    //3. 条件查询带分页
    @RequestMapping("search")
    public String search(@RequestParam(defaultValue = "1",required = false) Integer page,
                         @RequestParam(defaultValue = "3",required = false) Integer pageSize,
                         StudentVo stud,
                         Model model){
        //3.1 分页查询学生列表
        PageResult<Student> pr = studentService.search(page,pageSize,stud);
        model.addAttribute("pr",pr);
        //3.2 查询所有班级
        List<Classes> classes = classesService.findAll();
        model.addAttribute("classes",classes);
        if (stud == null){
            stud = new StudentVo();
        }
        model.addAttribute("stud",stud);
        return "student/list";
    }

    //4. 添加学生
    @RequestMapping("add")
    public String add(Student student){
        studentService.add(student);
        return "redirect:/student/search";
    }

    //5. 修改学生
    @RequestMapping("update")
    public String update(Student student){
        studentService.update(student);
        return "redirect:/student/search";
    }

    //6. 删除学生
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable int id){
        studentService.delete(id);
        return "redirect:/student/search";
    }
}
